import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'controller.dart';
import '../../../common/models/server_model.dart';

class ServerMonitorPage extends GetView<ServerMonitorController> {
  const ServerMonitorPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(  
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: () {
            Get.back();
          },
        ),
        title: Obx(() => Text(controller.server.value?.name ?? '服务器监控')),
        actions: [
          // 自动刷新开关
          Obx(() => IconButton(
            icon: Icon(
              controller.autoRefresh.value ? Icons.refresh : Icons.refresh_outlined,
              color: controller.autoRefresh.value ? Colors.green : null,
            ),
            onPressed: () => controller.toggleAutoRefresh(!controller.autoRefresh.value),
            tooltip: controller.autoRefresh.value ? '关闭自动刷新' : '开启自动刷新',
          )),
          // 设置菜单（刷新间隔）
          PopupMenuButton<int>(
            icon: const Icon(Icons.more_vert),
            onSelected: (value) => controller.setRefreshInterval(value),
            tooltip: '刷新间隔设置',
            itemBuilder: (context) => [
              const PopupMenuItem(
                value: 3,
                child: Text('刷新间隔: 3秒'),
              ),
              const PopupMenuItem(
                value: 5,
                child: Text('刷新间隔: 5秒'),
              ),
              const PopupMenuItem(
                value: 10,
                child: Text('刷新间隔: 10秒'),
              ),
              const PopupMenuItem(
                value: 30,
                child: Text('刷新间隔: 30秒'),
              ),
            ],
          ),
        ],
      ),
      body: Obx(() {
        if (controller.isLoading.value && controller.statusData.value == null) {
          return const Center(child: CircularProgressIndicator());
        }

        if (controller.errorMessage.value.isNotEmpty && controller.statusData.value == null) {
          return _buildErrorView();
        }

        return RefreshIndicator(
          onRefresh: controller.fetchMonitoringData,
          child: SingleChildScrollView(
            physics: const AlwaysScrollableScrollPhysics(),
            padding: const EdgeInsets.all(12),  // 紧凑内边距：16 -> 12
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 刷新提示
                _buildRefreshInfo(),
                const SizedBox(height: 12),  // 紧凑间距：16 -> 12
                
                // CPU 详细信息
                _buildCpuCard(),
                const SizedBox(height: 12),  // 紧凑间距：16 -> 12
                
                // 内存详细信息
                _buildMemoryCard(),
                const SizedBox(height: 12),  // 紧凑间距：16 -> 12
                
                // 磁盘详细信息
                _buildDiskCard(),
                const SizedBox(height: 12),  // 紧凑间距：16 -> 12
                
                // 系统信息
                _buildSystemInfoCard(),
              ],
            ),
          ),
        );
      }),
    );
  }

  /// 构建刷新信息
  Widget _buildRefreshInfo() {
    return Obx(() {
      final data = controller.statusData.value;
      if (data == null) return const SizedBox.shrink();
      
      return Container(
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),  // 紧凑内边距：12/8 -> 10/6
        decoration: BoxDecoration(
          color: Colors.blue[50],
          borderRadius: BorderRadius.circular(8),
          border: Border.all(color: Colors.blue[200]!),
        ),
        child: Row(
          children: [
            Icon(Icons.access_time, size: 14, color: Colors.blue[700]),  // 紧凑图标：16 -> 14
            const SizedBox(width: 6),  // 紧凑间距：8 -> 6
            Text(
              '最后更新: ${_formatTime(data.timestamp)}',
              style: TextStyle(fontSize: 11, color: Colors.blue[700]),  // 紧凑字体：12 -> 11
            ),
            const Spacer(),
            if (controller.autoRefresh.value) ...[
              Icon(Icons.timer, size: 14, color: Colors.green[700]),  // 倒计时图标
              const SizedBox(width: 4),
              Obx(() => Text(
                '${controller.nextRefreshIn.value}秒后刷新',
                style: TextStyle(fontSize: 11, color: Colors.green[700], fontWeight: FontWeight.w600),
              )),
            ],
          ],
        ),
      );
    });
  }

  /// 构建 CPU 卡片
  Widget _buildCpuCard() {
    return Obx(() {
      final data = controller.statusData.value;
      if (data == null) return const SizedBox.shrink();
      
      return Card(
        elevation: 2,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        child: Padding(
          padding: const EdgeInsets.all(12),  // 紧凑内边距：16 -> 12
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Icon(Icons.memory, color: Colors.blue[700], size: 20),  // 紧凑图标：24 -> 20
                  const SizedBox(width: 10),  // 紧凑间距：12 -> 10
                  const Text(
                    'CPU 使用率',
                    style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),  // 紧凑字体：18 -> 15
                  ),
                  const Spacer(),
                  Text(
                    '${data.cpuUsage.toStringAsFixed(1)}%',
                    style: TextStyle(
                      fontSize: 20,  // 紧凑字体：24 -> 20
                      fontWeight: FontWeight.bold,
                      color: _getColorForPercentage(data.cpuUsage),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 12),  // 紧凑间距：16 -> 12
              
              // CPU 使用率进度条
              ClipRRect(
                borderRadius: BorderRadius.circular(6),  // 紧凑圆角：8 -> 6
                child: LinearProgressIndicator(
                  value: data.cpuUsage / 100,
                  minHeight: 16,  // 紧凑高度：20 -> 16
                  backgroundColor: Colors.grey[200],
                  valueColor: AlwaysStoppedAnimation<Color>(
                    _getColorForPercentage(data.cpuUsage),
                  ),
                ),
              ),
              
              const SizedBox(height: 12),  // 紧凑间距：16 -> 12
              
              // CPU 状态说明
              _buildStatusText(data.cpuUsage),
            ],
          ),
        ),
      );
    });
  }

  /// 构建内存卡片
  Widget _buildMemoryCard() {
    return Obx(() {
      final data = controller.statusData.value;
      if (data == null) return const SizedBox.shrink();
      
      return Card(
        elevation: 2,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        child: Padding(
          padding: const EdgeInsets.all(12),  // 紧凑内边距：16 -> 12
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Icon(Icons.memory_outlined, color: Colors.orange[700], size: 20),  // 紧凑图标：24 -> 20
                  const SizedBox(width: 10),  // 紧凑间距：12 -> 10
                  const Text(
                    '内存使用率',
                    style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),  // 紧凑字体：18 -> 15
                  ),
                  const Spacer(),
                  Text(
                    '${data.memoryUsage.toStringAsFixed(1)}%',
                    style: TextStyle(
                      fontSize: 20,  // 紧凑字体：24 -> 20
                      fontWeight: FontWeight.bold,
                      color: _getColorForPercentage(data.memoryUsage),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 12),  // 紧凑间距：16 -> 12
              
              // 内存使用率进度条
              ClipRRect(
                borderRadius: BorderRadius.circular(6),  // 紧凑圆角：8 -> 6
                child: LinearProgressIndicator(
                  value: data.memoryUsage / 100,
                  minHeight: 16,  // 紧凑高度：20 -> 16
                  backgroundColor: Colors.grey[200],
                  valueColor: AlwaysStoppedAnimation<Color>(
                    _getColorForPercentage(data.memoryUsage),
                  ),
                ),
              ),
              
              const SizedBox(height: 12),  // 紧凑间距：16 -> 12
              
              // 内存详细信息
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  _buildMemoryInfo(
                    '已使用',
                    _formatBytes(data.usedMemory),
                    Colors.orange,
                  ),
                  _buildMemoryInfo(
                    '可用',
                    _formatBytes(data.availableMemory),
                    Colors.green,
                  ),
                  _buildMemoryInfo(
                    '总内存',
                    _formatBytes(data.totalMemory),
                    Colors.blue,
                  ),
                ],
              ),
              
              const SizedBox(height: 12),  // 紧凑间距：16 -> 12
              _buildStatusText(data.memoryUsage),
            ],
          ),
        ),
      );
    });
  }

  /// 构建磁盘卡片
  Widget _buildDiskCard() {
    return Obx(() {
      final data = controller.statusData.value;
      if (data == null) return const SizedBox.shrink();
      
      return Card(
        elevation: 2,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        child: Padding(
          padding: const EdgeInsets.all(12),  // 紧凑内边距：16 -> 12
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Icon(Icons.storage, color: Colors.green[700], size: 20),  // 紧凑图标：24 -> 20
                  const SizedBox(width: 10),  // 紧凑间距：12 -> 10
                  const Text(
                    '磁盘使用率',
                    style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),  // 紧凑字体：18 -> 15
                  ),
                  const Spacer(),
                  Text(
                    '${data.diskUsage.toStringAsFixed(1)}%',
                    style: TextStyle(
                      fontSize: 20,  // 紧凑字体：24 -> 20
                      fontWeight: FontWeight.bold,
                      color: _getColorForPercentage(data.diskUsage),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 12),  // 紧凑间距：16 -> 12
              
              // 磁盘使用率进度条
              ClipRRect(
                borderRadius: BorderRadius.circular(6),  // 紧凑圆角：8 -> 6
                child: LinearProgressIndicator(
                  value: data.diskUsage / 100,
                  minHeight: 16,  // 紧凑高度：20 -> 16
                  backgroundColor: Colors.grey[200],
                  valueColor: AlwaysStoppedAnimation<Color>(
                    _getColorForPercentage(data.diskUsage),
                  ),
                ),
              ),
              
              const SizedBox(height: 12),  // 紧凑间距：16 -> 12
              
              // 磁盘详细信息
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  _buildMemoryInfo(
                    '已使用',
                    _formatBytes(data.usedDisk),
                    Colors.orange,
                  ),
                  _buildMemoryInfo(
                    '可用',
                    _formatBytes(data.availableDisk),
                    Colors.green,
                  ),
                  _buildMemoryInfo(
                    '总容量',
                    _formatBytes(data.totalDisk),
                    Colors.blue,
                  ),
                ],
              ),
              
              const SizedBox(height: 12),  // 紧凑间距：16 -> 12
              _buildStatusText(data.diskUsage),
            ],
          ),
        ),
      );
    });
  }

  /// 构建系统信息卡片
  Widget _buildSystemInfoCard() {
    return Obx(() {
      final data = controller.statusData.value;
      final server = controller.server.value;
      if (data == null || server == null) return const SizedBox.shrink();
      
      return Card(
        elevation: 2,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        child: Padding(
          padding: const EdgeInsets.all(12),  // 紧凑内边距：16 -> 12
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Icon(Icons.info_outline, color: Colors.purple[700], size: 20),  // 紧凑图标：24 -> 20
                  const SizedBox(width: 10),  // 紧凑间距：12 -> 10
                  const Text(
                    '系统信息',
                    style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),  // 紧凑字体：18 -> 15
                  ),
                ],
              ),
              const SizedBox(height: 12),  // 紧凑间距：16 -> 12
              
              _buildInfoRow('服务器名称', server.name),
              const Divider(height: 20),  // 紧凑高度：24 -> 20
              _buildInfoRow('IP 地址', '${server.host}:${server.port}'),
              const Divider(height: 20),  // 紧凑高度：24 -> 20
              _buildInfoRow('用户名', server.username),
              
              if (data.hostname != null) ...[
                const Divider(height: 20),  // 紧凑高度：24 -> 20
                _buildInfoRow('主机名', data.hostname!),
              ],
              
              if (data.osVersion != null) ...[
                const Divider(height: 20),  // 紧凑高度：24 -> 20
                _buildInfoRow('操作系统', data.osVersion!),
              ],
              
              if (data.uptime != null) ...[
                const Divider(height: 20),  // 紧凑高度：24 -> 20
                _buildInfoRow('运行时间', data.uptime!),
              ],
            ],
          ),
        ),
      );
    });
  }

  /// 构建错误视图
  Widget _buildErrorView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.error_outline, size: 48, color: Colors.red[300]),  // 紧凑图标：64 -> 48
          const SizedBox(height: 12),  // 紧凑间距：16 -> 12
          Text(
            controller.errorMessage.value,
            style: TextStyle(fontSize: 14, color: Colors.grey[600]),  // 紧凑字体：16 -> 14
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 20),  // 紧凑间距：24 -> 20
          ElevatedButton.icon(
            onPressed: controller.fetchMonitoringData,
            icon: const Icon(Icons.refresh, size: 18),  // 紧凑图标
            label: const Text('重试', style: TextStyle(fontSize: 13)),  // 紧凑字体
            style: ElevatedButton.styleFrom(
              minimumSize: const Size(0, 36),  // 标准按钮高度
              padding: const EdgeInsets.symmetric(vertical: 8),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建内存/磁盘信息
  Widget _buildMemoryInfo(String label, String value, Color color) {
    return Column(
      children: [
        Text(
          label,
          style: TextStyle(
            fontSize: 11,  // 紧凑字体：12 -> 11
            color: Colors.grey[600],
          ),
        ),
        const SizedBox(height: 3),  // 紧凑间距：4 -> 3
        Text(
          value,
          style: TextStyle(
            fontSize: 14,  // 紧凑字体：16 -> 14
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
      ],
    );
  }

  /// 构建信息行
  Widget _buildInfoRow(String label, String value) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(
          width: 90,  // 紧凑宽度：100 -> 90
          child: Text(
            '$label:',
            style: const TextStyle(
              fontWeight: FontWeight.w500,
              fontSize: 12,  // 紧凑字体：14 -> 12
            ),
          ),
        ),
        Expanded(
          child: Text(
            value,
            style: TextStyle(
              fontSize: 12,  // 紧凑字体：14 -> 12
              color: Colors.grey[700],
            ),
          ),
        ),
      ],
    );
  }

  /// 构建状态文本
  Widget _buildStatusText(double percentage) {
    final String status;
    final Color color;
    
    if (percentage < 60) {
      status = '状态良好';
      color = Colors.green;
    } else if (percentage < 80) {
      status = '使用率偏高';
      color = Colors.orange;
    } else {
      status = '使用率过高，建议优化';
      color = Colors.red;
    }
    
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),  // 紧凑内边距：12/8 -> 10/6
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(6),  // 紧凑圆角：8 -> 6
        border: Border.all(color: color.withOpacity(0.3)),
      ),
      child: Row(
        children: [
          Icon(
            percentage < 60 ? Icons.check_circle : Icons.warning,
            size: 14,  // 紧凑图标：16 -> 14
            color: color,
          ),
          const SizedBox(width: 6),  // 紧凑间距：8 -> 6
          Text(
            status,
            style: TextStyle(
              fontSize: 11,  // 紧凑字体：12 -> 11
              color: color,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }

  /// 根据百分比获取颜色
  Color _getColorForPercentage(double percentage) {
    if (percentage < 60) {
      return Colors.green;
    } else if (percentage < 80) {
      return Colors.orange;
    }
    return Colors.red;
  }

  /// 格式化字节大小
  String _formatBytes(int bytes) {
    if (bytes < 1024) {
      return '$bytes B';
    } else if (bytes < 1024 * 1024) {
      return '${(bytes / 1024).toStringAsFixed(1)} KB';
    } else if (bytes < 1024 * 1024 * 1024) {
      return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
    } else {
      return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(1)} GB';
    }
  }

  /// 格式化时间
  String _formatTime(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inSeconds < 60) {
      return '${difference.inSeconds} 秒前';
    } else if (difference.inMinutes < 60) {
      return '${difference.inMinutes} 分钟前';
    } else {
      return '${difference.inHours} 小时前';
    }
  }
}

